package service

import (
	"fitness/internal/dao"
	"fitness/internal/entity/system"
	"fitness/pkg/utils/R"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"strconv"
)

type DictService struct {
	SysDictDao *dao.SysDictDao
	Log        *zap.Logger
}

func NewDictService(SysDictDao *dao.SysDictDao, Log *zap.Logger) *DictService {
	return &DictService{
		SysDictDao: SysDictDao,
		Log:        Log,
	}
}

// 获取字典
func (dictService *DictService) GetDictOptions(c *gin.Context) {
	code := c.Param("code")
	options := dictService.SysDictDao.ListDictItemsByCode(code)
	c.JSON(http.StatusOK, R.ReturnSuccess(options))
}

func (dictService *DictService) GetDictPage(context *gin.Context) {
	var pageQuery system.SysDictPageQuery
	err := context.ShouldBindQuery(&pageQuery)
	if err != nil {
		context.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	users, err := dictService.SysDictDao.GetDictPage(pageQuery)
	if err != nil {
		context.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	context.JSON(http.StatusOK, R.ReturnSuccess(users))
}

func (dictService *DictService) GetDictForm(context *gin.Context) {
	dictIdStr := context.Param("dictId")
	// 尝试将字符串转换为整数
	dictId, err := strconv.ParseUint(dictIdStr, 10, 64)
	if err != nil {
		// 如果转换失败，返回错误响应
		context.JSON(http.StatusOK, "Invalid ID")
		return
	}
	form, err := dictService.SysDictDao.GetDictForm(dictId)
	if err != nil {
		context.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	context.JSON(http.StatusOK, R.ReturnSuccess(form))
}

func (dictService *DictService) SaveDict(context *gin.Context) {
	var dict system.DictPageVO
	err := context.ShouldBindJSON(&dict)
	if err != nil {
		context.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	f, err := dictService.SysDictDao.SaveDict(dict)
	if err != nil {
		context.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	context.JSON(http.StatusOK, R.ReturnSuccess(f))
}

func (dictService *DictService) DeleteDict(context *gin.Context) {
	dictIds := context.Param("dictIds")
	f, err := dictService.SysDictDao.DeleteDict(dictIds)
	if err != nil {
		context.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	context.JSON(http.StatusOK, R.ReturnSuccess(f))
}

func (dictService *DictService) UpdateDict(context *gin.Context) {
	var form system.DictForm
	err := context.ShouldBindJSON(&form)
	if err != nil {
		dictService.Log.Error("绑定失败", zap.Error(err))
		context.JSON(http.StatusOK, "修改字典信息失败")
		return
	}
	param := context.Param("dictId")
	id, err := strconv.ParseUint(param, 10, 64)
	if err != nil {
		dictService.Log.Error("绑定失败", zap.Error(err))
		context.JSON(http.StatusOK, "修改字典信息失败")
		return
	}
	result, err := dictService.SysDictDao.UpdateDict(id, form)
	if err != nil {
		context.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	context.JSON(http.StatusOK, R.ReturnSuccess(result))
}
